<?php
/**
 * @title 75. 颜色分类 - 原地操作
 * @author start2004
 */

// ini_set("memory_limit", "128M");

class Solution {

    /**
     * @param Integer[] $nums
     * @return NULL
     */
    function sortColors(&$nums) {

        /**
         * @since 2020-10-12 转移蓝色球的数量
         */
        $move = 0;

        /**
         * @since 2020-10-12 迭代
         */
        for($i=0, $len = count($nums); $i<$len; $i++){
            /**
             * @since 2020-10-12 0=红, 1=白, 2=蓝
             */
            $val = $nums[$i];
            // echo "i={$i}, val={$val},";

            if($val == 0){
                /**
                 * @since 2020-10-12 放到数组头部
                 */
                unset($nums[$i]);
                array_unshift($nums, $val);
                $i -= $move;
                $len -= $move;
                $move = 0;
            } elseif($val == 2) {
                /**
                 * @since 2020-10-12 放到数组尾部
                 */
                unset($nums[$i]);
                $nums[] = $val;
                $move++;
            } else {
                /**
                 * @since 2020-10-12 白色不动
                 */
            }
            // echo "nums=[", implode(",", $nums) ,"]", PHP_EOL;
        }

        /**
         * @return
         */
        return $nums;
    }
}



/**
 * @url http://127.0.0.1/leetcode/202008/2020.08.05_3.php
 */
$datas = [
    [2,0,2,1,1,0],
    [1,2,2,2,2,0,0,0,1,1],
];

include_once dirname(__DIR__) . DIRECTORY_SEPARATOR ."xhprof.php";
$xhprof = new Xhprof();
foreach ($datas as $data){
    var_dump($data);

    $obj = new Solution();
    $result = $obj->sortColors($data);
    var_dump($result);
    echo str_repeat("<br>", 3);
}
$xhprof->end();
